import React, { PureComponent } from 'react';
import router from 'umi/router';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Row, Button, Input, message, Modal, InputNumber, Col, Divider } from 'antd';
import { connect } from 'dva';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
@Form.create()
@connect(({ supplymanage, loading }) => ({
  supplymanage,
  loading: loading.models.supplymanage,
}))
class BasicList extends PureComponent {
  state = {
    // 删除
    supplyName: '',
    supplyPrice: '',
    modifyVisible: false,
    selectedRows: [],
    selectedKeys: [],
  };

  componentDidMount() {
    this.getList();
  }

  // 录入数据
  insertOne = () => {
    router.push('/filemanage/supplymanage/add');
  };

  getList = (current = 1, pageSize = 10, isClear = true) => {
    const { dispatch, form } = this.props;
    if (isClear) {
      this.setState({
        selectedKeys: [],
        selectedRows: [],
      });
    }
    form.validateFields(['rcrdSuppNameList', 'priceList'], (err, value) => {
      if (err) return;
      dispatch({
        type: 'supplymanage/getList',
        payload: {
          pageArg: {
            currentPage: current,
            pageSize,
          },
          rcrdSuppVo: {
            rcrdSuppName: (value.rcrdSuppNameList && value.rcrdSuppNameList.trim()) || '',
            price: value.priceList  || '',
          },
        },
      });
    });
  };

  nameChange = e => {
    const { form } = this.props;
    form.setFieldsValue({
      rcrdSuppName: e.target.value,
    });
  };

  priceChange = value => {
    const { form } = this.props;
    form.setFieldsValue({
      price: value,
    });
  };

  modifyHandleOk = e => {
    e.preventDefault();
    const {
      dispatch,
      supplymanage: {
        pageData: { pagination },
      },
      form,
    } = this.props;
    const { rcrdSuppId, vno } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'supplymanage/modifyHandleOk',
          payload: {
            price: values.price,
            rcrdSuppName: values.rcrdSuppName,
            rcrdSuppId,
            vno,
          },
        }).then(tempData => {
          this.setState({
            modifyVisible: false,
          });
          if (tempData.success) {
            this.getList(pagination.current, pagination.pageSize);
            message.success('修改成功！');
          } else {
            message.warning('修改失败！');
          }
        });
      }
    });
  };

  modifyHandleCancel = () => {
    this.setState({
      modifyVisible: false,
    });
  };

  modify = (id, name, price, vno) => {
    const { form } = this.props;
    this.setState({
      modifyVisible: true,
      rcrdSuppId: id,
      vno,
    });
    form.setFieldsValue({
      rcrdSuppName: name,
      price,
    });
  };

  deleteItem = (id, vno) => {
    const {
      dispatch,
      supplymanage: {
        pageData: { pagination },
      },
    } = this.props;
    Modal.confirm({
      title: '删除',
      content: '确认删除吗？',
      icon: <QuestionCircleOutlined />,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'supplymanage/deleteItem',
          payload: {
            rcrdSuppId: id,
            vno,
          },
        }).then(tempData => {
          if (tempData.success) {
            this.getList(pagination.current, pagination.pageSize);
          }
        });
      },
    });
  };

  addNameChange = e => {
    const { form } = this.props;
    form.setFieldsValue({
      addName: e.target.value,
    });
  };

  addPriceChange = value => {
    const { form } = this.props;
    form.setFieldsValue({
      addPrice: value,
    });
  };

  handleSelectRows = (selectedRows, selectedKeys) => {
    this.setState({ selectedRows, selectedKeys });
  };

  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize, false);
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      supplymanage: { pageData, formFieldsValue },
    } = this.props;
    const { selectedRows, selectedKeys, modifyVisible, supplyName, supplyPrice } = this.state;
    const columns = [
      {
        title: '供应商名称',
        dataIndex: 'rcrdSuppName',
        key: 'rcrdSuppName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
      },
      {
        title: '每人每月价格',
        dataIndex: 'price',
        key: 'price',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: (text, record) => (
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <span
              style={{ color: '#1890FF', cursor: 'pointer' }}
              onClick={() =>
                this.modify(record.rcrdSuppId, record.rcrdSuppName, record.price, record.vno)
              }
            >
              {' '}
              修改
            </span>
            <Divider type="vertical" />
            <span
              style={{ color: '#1890FF', cursor: 'pointer' }}
              onClick={() => this.deleteItem(record.rcrdSuppId, record.vno)}
            >
              {' '}
              删除
            </span>
          </div>
        ),
      },
    ];

    const formItemLayout = {
      labelCol: { md: { span: 8 } },
      wrapperCol: { md: { span: 16 } },
    };

    return (
      <div>
        <PageHeaderWrapper>
          <Card className={styles.searchCard}>
            <div className={styles.tableListForm}>
              <Form layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={8} sm={24}>
                    <FormItem {...formItemLayout} label="供应商名称">
                      {getFieldDecorator('rcrdSuppNameList', {
                        initialValue: formFieldsValue.rcrdSuppName,
                      })(<Input placeholder="请输入供应商名称" style={{ width: '100%' }} />)}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem {...formItemLayout} label="每人每月价格">
                      {getFieldDecorator('priceList', {
                        initialValue: formFieldsValue.price,
                      })(<InputNumber min={1} max={1000} style={{ width: '100%' }} />)}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <span className={styles.submitButtons}>
                      <Button
                        type="primary"
                        style={{ marginLeft: 20 }}
                        onClick={() => this.getList()}
                      >
                        {' '}
                        查询{' '}
                      </Button>
                    </span>
                  </Col>
                </Row>
              </Form>
            </div>
          </Card>
          <Card className={styles.tabCard}>
            <Row style={{ margin: '12px 0px 16px' }}>
              <Button type="primary" onClick={this.insertOne}>
                <PlusOutlined />
                新增{' '}
              </Button>
            </Row>

            <StandardTable
              selectedRows={selectedRows}
              selectedRowKeys={selectedKeys}
              loading={loading}
              data={pageData}
              columns={columns}
              rowKey="rcrdSuppId"
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />

            <Modal
              title="修改"
              visible={modifyVisible}
              onOk={this.modifyHandleOk}
              onCancel={this.modifyHandleCancel}
            >
              <Form>
                <FormItem {...formItemLayout} label="供应商名称">
                  {getFieldDecorator('rcrdSuppName', {
                    rules: [{ required: true, message: '请输入供应商名称' }],
                    initialValue: supplyName,
                  })(
                    <Input
                      placeholder="请输入供应商名称"
                      style={{ width: 200 }}
                      onChange={this.nameChange}
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="每人每月价格">
                  {getFieldDecorator('price', {
                    rules: [{ required: true, message: '请输入每人每月价格' }],
                    initialValue: supplyPrice,
                  })(<InputNumber min={1} max={1000} onChange={this.priceChange} />)}
                </FormItem>
              </Form>
            </Modal>
          </Card>
        </PageHeaderWrapper>
      </div>
    );
  }
}

export default BasicList;
